package com.xl.basic.aop.aspect;

import com.xl.basic.annotation.LoginIgnored;
import com.xl.basic.annotation.LoginValidated;
import com.xl.basic.entity.Result;
import com.xl.basic.entity.ResultEnums;
import com.xl.basic.entity.ResultException;
import com.xl.basic.entity.UserInfo;
import com.xl.basic.utils.LoginUtils;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 对登录验证
 * 标注@LoginIgnored不进行登录验证
 * class标注@LoginIgnored，action标注@LoginValidated进行登录验证
 *
 * @author 钟勇
 * Create in 2023/8/25 10:31
 */
@Component
@Aspect
@Order(1)
@RequiredArgsConstructor
public class LoginAspect {

    /**
     * controller默认全部要登录鉴权，除非@LoginIgnored
     *
     * @param joinPoint joinPoint
     */
    @Before("execution(* com.xl..*.controller..*.*(..))")
    public void loginValidate(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();

        Method method = ((MethodSignature) signature).getMethod();
        Class<?> declaring = signature.getDeclaringType();

        //判断方法上的登录忽略注解
        LoginIgnored loginIgnored = method.getAnnotation(LoginIgnored.class);
        if (loginIgnored != null) {
            return;
        }

        //判断action上是否有@LoginValidated
        LoginValidated loginValidated = method.getAnnotation(LoginValidated.class);
        if (loginValidated == null) {
            //判断class上的登录忽略注解
            loginIgnored = declaring.getAnnotation(LoginIgnored.class);
            if (loginIgnored != null) {
                return;
            }
        }

        Result<UserInfo> userInfoRes = LoginUtils.getUserInfo();
        if (userInfoRes.isErr()) {
            throw new ResultException(ResultEnums.LoginError.getResult(userInfoRes.getMessage()));
        }
    }

}
